package com.tjetc.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tjetc.common.JsonResult;
import com.tjetc.dao.TagsMapper;
import com.tjetc.entity.City;
import com.tjetc.entity.Spot;
import com.tjetc.entity.SpotRankTag;
import com.tjetc.entity.Tag;
import com.tjetc.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TagServiceImpl implements TagService {
    @Autowired
    TagsMapper tagsMapper;
    @Override
    public JsonResult addTag(String tagName) {
        Tag t=new Tag();
        t.setState("待审核");
        t.setTagName(tagName);
        tagsMapper.insert(t);
    return JsonResult.success("添加成功");
    }

    @Override
    public JsonResult allTag() {
        List<Tag> tags=tagsMapper.getActiveTags("active");
        return JsonResult.success("查询标签成功",tags);
    }

    @Override
    public JsonResult test() {
         updateSpotTags();
        return JsonResult.success("查询标签成功");
    }

    @Scheduled(cron = "0 0 0 * * ?")
    public void updateSpotTags() {
        List<String> tagsList = tagsMapper.getSpotTag();
        Map<Long, Long> tagCountMap = new HashMap<>();

        for (String tagsJson : tagsList) {
            if (tagsJson == null || tagsJson.isEmpty()) continue;
            try {
                List<Long> tagIds = new ObjectMapper().readValue(tagsJson, new TypeReference<List<Long>>() {});
                for (Long tagId : tagIds) {
                    tagCountMap.put(tagId, tagCountMap.getOrDefault(tagId, 0L) + 1);
                }
            } catch (Exception e) {
                e.printStackTrace(); // 可换成日志
            }
        }

        for (Map.Entry<Long, Long> entry : tagCountMap.entrySet()) {
            tagsMapper.updateHotnessByTagId(entry.getKey(), entry.getValue());
        }



    }



}
